package com.wormhole.wormholemanagement.controller;

import com.fasterxml.jackson.annotation.JsonProperty;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.tags.Tag;
import lombok.Getter;
import org.apache.tomcat.util.http.fileupload.FileUploadException;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;
import java.io.IOException;
import java.nio.file.AccessDeniedException;
import java.nio.file.Files;
import java.nio.file.Path;

@Getter
@RestController
@RequestMapping("/api/upload")
@Tag(name = "文件上传")
public class FileUploadController {

    @Value("${app.upload.dir}")
    private String uploadBaseDir;

    @PostMapping("/image")
    @Operation(summary = "上传文件")
    public ResponseEntity<?> uploadImage(
            @RequestParam("file") MultipartFile file,
            @RequestParam(value = "path", required = false) String subPath,
            @RequestParam(value = "fileName", required = false) String fileName) throws FileUploadException {

        try {
            // 验证文件
            if (file.isEmpty()) {
                throw new FileUploadException("上传文件不能为空");
            }

            // 构建完整上传路径
            Path uploadDir = Path.of(uploadBaseDir + subPath);
            System.out.println("上传路径: " + uploadDir);

            // 创建目录（如果不存在）
            createDirectoryIfNotExists(uploadDir);

            // 保存文件
            Path filePath = uploadDir.resolve(fileName);
            file.transferTo(filePath.toFile());
            return ResponseEntity.ok().body(
                    new UploadResponse(
                            true,
                            "文件上传成功",
                            fileName,
                            filePath.toString(),
                            filePath.toString()  // 使用标准化路径
                    ));
        } catch (IOException e) {
            throw new FileUploadException("文件上传失败: " + e.getMessage());
        }
    }

    private void createDirectoryIfNotExists(Path path) throws IOException {
        if (!Files.exists(path)) {
            try {
                Files.createDirectories(path);
            } catch (AccessDeniedException e) {
                throw new IOException("无权限创建目录: " + path);
            }
        }
    }

    private static class UploadResponse {
        @JsonProperty("success")
        private boolean success;

        @JsonProperty("message")
        private String message;

        @JsonProperty("fileName")
        private String fileName;

        @JsonProperty("filePath")
        private String filePath;

        @JsonProperty("fileUrl")
        private String fileUrl;

        public UploadResponse(boolean success, String message, String fileName, String filePath, String fileUrl) {
            this.success = success;
            this.message = message;
            this.fileName = fileName;
            this.filePath = filePath;
            this.fileUrl = fileUrl;
        }
    }
}